/*
 * 	type
 *  Adds type conversion capabilities to objx(o).type
 */
 
objx.requires("objx.is", "objx.type");

// save the original type getter
objx.fn.getType = objx.fn.type;

objx.fn.type = function() {

	if (arguments.length === 0) {
	
		// return the type of the object
		return this.getType();
		
	} else {
	
		var 
			_obj = this.obj(),
			fromType = typeof _obj,
			toType = arguments[0].toString(),
			i, l
		;
	
		if (fromType === toType) { return this; }
	
		// cast the current object to another
		switch (toType) {
			case "number":
			
				if (!this.is("something")) { this.obj(0); return this; }

				if (fromType == "boolean") {
				
					if (_obj) {
						return objx(1);
					} else {
						return objx(0);
					}
						
				} else {
				
					return objx(parseFloat(_obj));
				
				}
			
				break;
			case "string":
				if (!this.is("something")) { this.obj(""); }
				this.obj(this.obj().toString());
				break;
			case "boolean":
			
				if (!this.is("something")) { this.obj(false); }
			
				switch (fromType) { 
					case "string":
						return objx(_obj === "true");
						break;
					case "number":
						return objx(!(_obj === 0));
						break;
				}
			
				break;
			case "function":
			
				if (fromType != "function") {
					this.obj(
						objx.bind(function(value){
							return value;
						}, null, this.obj())
					);
				}

				break;
			case "array":
			
				switch (fromType) {
					case "string":
					
						var 
							s = this.obj(),
							chars = []
						;
						
						for (i = 0, l = this.size(); i < l; i++) {
							chars.push(s.charAt(i));
						}
						
						// set the chars
						return objx(chars);
					
						break;
					case "number":
					
						var numbers = [];
						
						for (i = 0, l = this.obj(); i < l; i++) {
							numbers.push(i);
						}
						
						return objx(numbers);
					
						break;
					case "boolean":
					
						return objx([this.obj()]);
					
						break;
				}
			
				break;
			default:
				objx.error("type", "type() doesn't know about the type '" + arguments[0] + "'.");
		}
		
		return this;
	
	}
	
};

objx.provides("objx.type");